<template>
    <div>
        <!-- 操作按钮 -->
        <div class="actions" v-permission="'manage_device'">
            <el-button type="primary" @click="handleEdit" size="small">编辑</el-button>
            <el-button type="info" v-if="currentMeter.engine_id === 18" size="small" @click="handleCommand">
                命令
            </el-button>
        </div>

        <!-- 编辑表计对话框 -->
        <el-dialog destroy-on-close :title="currentMeter ? '编辑表计' : '新增表计'" align-center v-model="dialogVisible">
            <MeterDialog @update:visible="handleUpdate" :pMeter="parent_meter"
                :id="currentMeter ? currentMeter.id : null" />
        </el-dialog>

        <!-- 命令对话框 - 上传时间配置 -->
        <el-dialog destroy-on-close title="设置上传时间" align-center v-model="commandDialogVisible" width="400px">
            <!-- 协议提示信息 -->
            <el-alert title="温馨提示" type="info" :closable="false" show-icon style="margin-bottom: 20px;">
                <template #default>
                    由于协议是被动型，设置会在下一次表上线推送时才能发送过去
                </template>
            </el-alert>

            <el-form :model="uploadTime" label-width="80px">
                <el-form-item label="小时">
                    <el-input-number v-model="uploadTime.hour" :min="0" :max="23" :step="1" />
                </el-form-item>

                <el-form-item label="分钟">
                    <el-input-number v-model="uploadTime.minute" :min="0" :max="59" :step="1" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="commandDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleCommandConfirm" :loading="commandLoading">
                    确认
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import MeterDialog from "@/components/meter/MeterDialog.vue";
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { useMeterStore } from "@/stores/meter.js";
import { addDeviceApi, getDeviceListApi, runDeviceCommandApi } from "../../../../../api/device";
import { handleError } from "@/utils/handleError";
import { getMeterInfoApi, updateMeterApi } from "../../../../../api/meter";
import { useCompanyStore } from "@/stores/company.js";

const props = defineProps({
    currentMeter: {
        type: Object,
        default: () => ({})
    },
    parent_meter: {
        type: Object,
        default: () => ({})
    }
});

const meterStore = useMeterStore();
const companyStore = useCompanyStore();
const emit = defineEmits(['meter-updated', 'refresh']);

const dialogVisible = ref(false);
const commandDialogVisible = ref(false);
const loading = ref(false);
const commandLoading = ref(false);

const uploadTime = reactive({
    hour: 23,
    minute: 0
});

/**
 * 打开编辑表计对话框
 */
function handleEdit() {
    dialogVisible.value = true;
}

/**
 * 打开命令对话框
 */
function handleCommand() {
    commandDialogVisible.value = true;
}

/**
 * 确认设置上传时间
 */
async function handleCommandConfirm() {
    try {
        commandLoading.value = true;
        await setMeterUploadTime(uploadTime.hour, uploadTime.minute);
        commandDialogVisible.value = false;
        ElMessage.success('上传时间设置成功');
        emit('meter-updated');
        emit('refresh');
    } catch (error) {
        handleError(error, '设置上传时间失败');
    } finally {
        commandLoading.value = false;
    }
}

/**
 * 更新表计信息
 */
async function handleUpdate() {
    dialogVisible.value = false;
    loading.value = true;
    try {
        const res = await getMeterInfoApi({
            id: props.currentMeter.id,
        });
        meterStore.setCurrentMeter(res.data[0]);
        emit("meter-updated");
        emit("refresh");
        ElMessage.success("表计信息已更新");
    } catch (err) {
        handleError(err, '更新表计信息失败');
    } finally {
        loading.value = false;
    }
}

/**
 * 获取设备列表
 */
async function getDeviceList() {
    const response = await getDeviceListApi({
        type: 1,
        offset: 0,
        limit: 500,
        company_id: companyStore.currentCompany.id,
    });
    return response.data;
}

/**
 * 根据名称查找设备
 */
async function findDeviceByName(name) {
    const deviceList = await getDeviceList();
    return deviceList.find((item) => item.name === name);
}

/**
 * 创建新设备
 */
async function createDevice(meterCode) {
    await addDeviceApi({
        name: meterCode,
        type: 1,
        engine_id: 18,
        company_id: companyStore.currentCompany.id
    });
    return await findDeviceByName(meterCode);
}

/**
 * 绑定设备到表计
 */
async function bindDeviceToMeter(meterId, deviceId) {
    await updateMeterApi({
        id: meterId,
        device_id: deviceId
    });
}

/**
 * 执行设备命令
 */
async function runCommand(device, hour, minute) {
    await runDeviceCommandApi({
        id: device.id,
        command_id: 1,
        raw: {
            hour: hour,
            minute: minute,
        }
    });
}

/**
 * 获取或创建设备并绑定到表计
 */
async function ensureDeviceBinding() {
    let device;

    if (!props.currentMeter.device_id) {
        // 表计未绑定设备，尝试查找或创建设备
        device = await findDeviceByName(props.currentMeter.meter_code);

        if (!device) {
            // 设备不存在，创建新设备
            device = await createDevice(props.currentMeter.meter_code);
            if (!device) {
                throw new Error('创建设备失败');
            }
        }

        // 绑定设备到表计
        await bindDeviceToMeter(props.currentMeter.id, device.id);
    } else {
        // 表计已绑定设备，直接获取设备信息
        device = await findDeviceByName(props.currentMeter.meter_code);
        if (!device) {
            throw new Error('未找到对应设备');
        }
    }

    return device;
}

/**
 * 设置表计上传时间
 */
async function setMeterUploadTime(hour, minute) {
    // 获取或创建设备并确保绑定
    const device = await ensureDeviceBinding();

    // 执行设置上传时间命令
    await runCommand(device, hour, minute);
}
</script>

<style scoped>
.actions {
    display: flex;
    gap: 10px;
}
</style>